<template>
    <div>
        <el-upload
                action="/upload"
                :limit="max"
                name="filedata"
                :file-list="files"
                :show-file-list="showFileList"
                :list-type="listType"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-exceed="handleExceed"
                :multiple="multiple">
            <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
<script>
  export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false
      };
    },
    props: {
      max: {
        type: Number,
        default: 10
      },
      files: {
        type: Array,
        default: function () {
          return [];
        }
      },
      multiple: {
        type: Boolean,
        default: false
      },
      showFileList: {
        type: Boolean,
        default: true
      },
      listType: {
        type: String,
        default: 'picture-card'
      }
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
        this.change(fileList);
      },
      handleSuccess(response, file, fileList) {
        this.change(fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleExceed() {
        this.$message.info('最多只能上传' + this.max + '个文件，您可以试试删除后再上传');
      },
      change(fileList) {
        let files = [];
        fileList.forEach(function (file) {
          if (!file.response) {
            files.push({
              id: file.id,
              file_url: file.url
            });
          } else {
            files.push({
              id: file.response.data.id,
              file_url: file.response.data.file_url
            });
          }
        });
        this.$emit('change', files);
      }
    }
  }
</script>